package com.carrot.common.mybatis;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/** BaseServiceImpl 基类 - 实现类
 * @author 刘红真*/
@Slf4j
@Transactional(readOnly = true)
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T>
    implements IBaseService<T> {

  @Override
  public <V> Page<T, V> findPage(Page<T, V> page) {
    return findPage(page, true);
  }

  @Override
  public <V> Page<T, V> findPage(Page<T, V> page, boolean isByCount) {
    QueryWrapper<T> queryWrapper = page.getQueryWrapper();
    if (null == queryWrapper) {
      queryWrapper = new QueryWrapper<>();
    }

    try {
      PageHelper.startPage(page.getPageNo(), page.getPageSize(), isByCount);
      List<T> list = this.list(queryWrapper);
      PageInfo<T> info = new PageInfo<>(list);
      page.setTList(list);
      page.setTotal(info.getTotal());
    } finally {
      PageHelper.clearPage();
    }
    return page;
  }
}
